package com.aqielife.netty.simple.handler;

import com.alibaba.fastjson2.JSON;

import com.aqielife.netty.simple.ImServer;
import com.aqielife.netty.simple.Response;
import com.aqielife.netty.simple.command.ChatMsg;
import com.aqielife.netty.simple.enums.MessageType;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 处理不同聊天类型
 */
@Slf4j
public class ChatHandler {

    public static void execute(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
        try {
            ChatMsg msg = JSON.parseObject(frame.text(), ChatMsg.class);
            switch (MessageType.match(msg.getType())) {
                case PRIVATE -> {
                    if(StringUtils.isBlank(msg.getTarget())) {
                        ctx.channel().writeAndFlush(Response.ok("缺少接受者"));
                        return;
                    }
                    Channel channel = ImServer.USERS.get(msg.getTarget());
                    if (null == channel || !channel.isActive()) {
                        ctx.channel().writeAndFlush(Response.ok("消息发送失败, "+msg.getTarget()+"不在线"));
                    } else {
                        channel.writeAndFlush(Response.ok("私聊消息("+msg.getNickname()+")" +" : "+ msg.getContent()));
                    }
                }
                case GROUP -> ImServer.GROUP.writeAndFlush(Response.ok("群聊消息("+msg.getNickname()+")" +" : "+ msg.getContent()));
                default -> ctx.channel().writeAndFlush(Response.ok("不支持的消息类型"));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(Response.ok("发送消息格式错误"));
        }
    }
}
